<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="department_box box-card">
        <DeptOptions :row="company" :is-root="true" @onClickAdd="onClickAdd" />
        <!--        树形结构-->
        <el-tree :data="list" :props="defaultProps" :default-expand-all="true">
          <template v-slot="scope">
            <DeptOptions
              :row="scope.data"
              @onClickAdd="onClickAdd"
              @onClickEdit="onClickEdit"
              @onDel="getOrganizationalStructureData"
            />
          </template>
        </el-tree>
      </el-card>
    </div>
    <!--    弹出框-->
    <addDept
      ref="addDept"
      :row="deptRow"
      :show-dialog.sync="dialogVisible"
      @refreshData="getOrganizationalStructureData"
    />
  </div>
</template>

<script>
import { getDepartments } from '@/api/departments'
import { transListToTree } from '@/utils'
import DeptOptions from './components/deptOptions'
import addDept from '@/views/departments/components/addDept'

export default {
  name: 'Departments',
  components: {
    DeptOptions,
    addDept
  },
  data() {
    return {
      defaultProps: {
        label: 'name'
      },
      list: [], // 树形控件数据
      company: {}, // 公司信息
      dialogVisible: false, // 控制弹出框
      deptRow: {} // 点击添加存储点击添加那行的数据
    }
  },

  created() {
    this.getOrganizationalStructureData()
  },

  methods: {
    // 获取组织架构数据
    async getOrganizationalStructureData() {
      const { depts, companyName } = await getDepartments()
      this.company = { name: companyName, manager: '负责人', children: transListToTree(depts, '') }
      this.list = transListToTree(depts, '')
    },
    // 点击添加部门
    onClickAdd(data) {
      this.deptRow = data
      this.dialogVisible = true // 显示对话框
    },
    // 点击查看部门
    onClickEdit(data) {
      this.deptRow = data
      this.dialogVisible = true // 显示对话框
      setTimeout(() => {
        this.$refs.addDept.setForm()
      })
    }
  }
}
</script>

<style scoped lang='scss'>
.department_box {

  .el-tree {
    margin-top: 10px;
    border-top: 1px solid #ccc;
  }
}
</style>
